package servlets;

import java.net.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.*;
import org.xml.sax.*;

import data.*;
import util.*;

import java.util.*;


/**
 * Servlet implementation class ProcessRequest
 */
public class ProcessRecipeRequest extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProcessRecipeRequest() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//format our request
		
		String search = request.getParameter("search");
		String originalSearch = request.getParameter("search");
		if(search!=null && originalSearch != null){
			
		originalSearch = originalSearch.replace(" ", "_");
		search = search.replace(" ", "+");
		search = search.replace(",","%2C");
		
		//setup http request for recipepuppy
		URL recipeRequest = new URL("http://www.recipepuppy.com/api/?i=" + search + "&format=xml");
        URLConnection rrConnect = recipeRequest.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(rrConnect.getInputStream()));
        String inputLine;
        
        String docData = "";
        while((inputLine = in.readLine()) != null){
        	docData += inputLine;
        }
        in.close();
        
        ArrayList<RecipeData> recipes = new ArrayList<RecipeData>();
        RecipeData cur = null;
        Node currN;
        Element currE;
        NodeList recElems;
        NodeList tmpNL;
        Element tmpE;
        try{
        	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        	DocumentBuilder db = dbf.newDocumentBuilder();
        	Document doc = db.parse(new InputSource(new ByteArrayInputStream(docData.getBytes("utf-8"))));
        	doc.getDocumentElement().normalize();

        	recElems = doc.getDocumentElement().getChildNodes();
        	for(int i = 0; i < 5; i++){
        	    //recElems.getLength()
        		currN = recElems.item(i);
        		if(currN.getNodeType() != Node.ELEMENT_NODE)
        			continue;
        		
        		cur = new RecipeData();
        		currE = (Element)currN;
        		
        		tmpNL = currE.getChildNodes();
        		for(int j = 0; j < tmpNL.getLength(); j++){
        			tmpE = (Element)tmpNL.item(j);
        			if(tmpE.getNodeName().equalsIgnoreCase("title")){
        				cur.setTitle(tmpE.getFirstChild().getNodeValue());
        			}
        			if(tmpE.getNodeName().equalsIgnoreCase("href")){
        				cur.setHref(tmpE.getFirstChild().getNodeValue());
        			}
        			if(tmpE.getNodeName().equalsIgnoreCase("ingredients")){
        				cur.setIngredients(tmpE.getFirstChild().getNodeValue());
        			}
        		}
        		
        		recipes.add(cur);
        	}
        }catch(Exception e){System.out.println(e);}
        
        
//        while ((inputLine = in.readLine()) != null){
//            System.out.println(inputLine);
//            if(inputLine.contains("<recipe>")){
//            	recipe = new RecipeData();
//            }else if(inputLine.contains("</recipe>")){
//            	recipes.add(recipe);
//            }else if(inputLine.contains("<title>")){
//            	recipe.setTitle(removeTag("title",inputLine));
//            }else if(inputLine.contains("<href>")){
//            	recipe.setHref(removeTag("<href>",inputLine));
//            }else if(inputLine.contains("<ingredients>")){
//            	recipe.setIngredients(removeTag("ingredients",inputLine));
//            }
//        }
        
        
        WineRecommender wineRecommender = new WineRecommender();
        //for each recipe, get wine recommended and data on the wine
        for(int i = 0; i < recipes.size(); i++){
        	
        	RecipeData rec = recipes.get(i);
        	ArrayList<Varietal> wines = wineRecommender.recommend(rec.getIngredients());
        	rec.setVarietals(wines);
        
        }
        WineRequester.getWineData(recipes);
        CheeseRequester cheeseReq= new CheeseRequester();
        ArrayList<CheeseData> cheeses= cheeseReq.getAllCheeses();

        //publish the results
        AtomPublisher.publishFeed(originalSearch, recipes);
        RDFPublisher.publishData(recipes, cheeses);
        org.jdom.Document returnDom = AtomPublisher.getFeed(originalSearch);
        request.setAttribute("xmlDom", returnDom);
        request.setAttribute("link", "http://localhost:8080/exist/atom/edit/FoodAndWine/" + originalSearch);
		}
        RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
        dispatcher.forward(request, response);
	}
	
	
	public void testPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	
	}

}
